#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <random>
#include <chrono>
using namespace std;

mutex mtx;
condition_variable cv;
bool packet_received = false;
bool ack_received = false;
int packet_id = 0;

// 模拟丢包
bool is_packet_lost() 
{
    static random_device rd;
    static mt19937 gen(rd());
    uniform_int_distribution<> dis(1, 10);

    return dis(gen) <= 2; 
}

// 发包
void sender() 
{
    while (true) 
    {
        unique_lock<mutex> lock(mtx);
        // 发包
        cout << "Sender: Sending packet " << packet_id << endl;
        // 模拟丢包
        if (!is_packet_lost()) 
        {
            packet_received = true;
            cv.notify_one();
        } 
        else 
        {
            cout << "Sender: Packet " << packet_id << " lost!" << endl;
        }
        // 等待确认信息
        cv.wait(lock, []{ return ack_received; });
        cout << "Sender: Received ACK for packet " << packet_id << endl;
        ack_received = false;
        packet_id++;
    }
}

void receiver() 
{
    while (true) 
    {
        unique_lock<mutex> lock(mtx);
        // 等包
        cv.wait(lock, []{ return packet_received; });
        cout << "Receiver: Received packet " << packet_id << endl;
        // 模拟丢包（ACK 丢包）
        if (!is_packet_lost()) 
        {
            cout << "Receiver: Sending ACK for packet " << packet_id << endl;
            ack_received = true;
        } 
        else 
        {
            cout << "Receiver: ACK for packet " << packet_id << " lost!" << endl;
        }

        packet_received = false;
        cv.notify_one();
    }
}

int main() {
    thread sender_thread(sender);
    thread receiver_thread(receiver);

    sender_thread.join();
    receiver_thread.join();

    return 0;
}
    